package com.wy.panda.common.page;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wy.panda.common.util.CollectionUtils;
import com.wy.panda.common.util.StringUtils;
import com.wy.panda.exception.PandaException;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

/**
 * 分页查询参数基类
 * @author wangyuan
 * @since 2020年3月21日 下午2:13:04
 *
 */
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class PageParam implements Serializable {
	
	public static final int DEF_PAGE = 1;
	public static final int DEF_LIMIT = 10;

	/**
	 * 
	 */
	private static final long serialVersionUID = -4934537808391229058L;
	/**
	 * 当前页码
	 */
	@ApiModelProperty(value = "当前页码，从1开始", example = "1")
	@Builder.Default
	private Integer page = DEF_PAGE;
	/**
	 * 每页显示记录数
	 */
	@ApiModelProperty(value = "每页显示记录数", example = "10")
	@Builder.Default
	private Integer limit = DEF_LIMIT;
	/**
	 * 排序信息
	 */
	@ApiModelProperty("排序信息")
	private List<PageOrderParam> orders;
	
	public PageParam(Integer page, Integer limit) {
		super();
		this.page = page == null ? DEF_PAGE : page;
		this.limit = limit == null ? DEF_LIMIT : limit;
	}
	
	public void addPageOrderParam(PageOrderParam param) {
		if(orders == null) {
			orders = new ArrayList<>();
		}
		orders.add(param);
	}
	
	public void addPageOrderParam(String field, String order) {
		if(StringUtils.isBlank(field)) {
			throw new PandaException("分页字段属性名不能为空");
		}
		
		PageOrderParam param = new PageOrderParam(field);
		if(StringUtils.isNotBlank(order) && PageOrderParam.ORDER_DESC.equals(order.toUpperCase())) {
			param.setOrder(PageOrderParam.ORDER_DESC);
		}
		addPageOrderParam(param);
	}
	
	public void addPageOrderParam(String field, boolean isAsc) {
		if(StringUtils.isBlank(field)) {
			throw new PandaException("分页字段属性名不能为空");
		}
		addPageOrderParam(new PageOrderParam(field, isAsc ? PageOrderParam.ORDER_ASC : PageOrderParam.ORDER_DESC));
	}
	
	public <T> IPage<T> page() {
        //分页对象
        Page<T> page = new Page<>(getPage(), getLimit());
        if(CollectionUtils.isEmpty(getOrders())) {
        	return page;
        }
        
        //排序字段
        for(PageOrderParam orderItem : getOrders()) {
        	if(PageOrderParam.ORDER_ASC.equalsIgnoreCase(orderItem.getOrder())) {
        		page.addOrder(OrderItem.asc(orderItem.getField()));
        	} else {
        		page.addOrder(OrderItem.desc(orderItem.getField()));
        	}
        }
        return page;
    }
}
